package com.harmony.pilot.agent.service;

import com.harmony.pilot.common.dto.LLMRequest;
import com.harmony.pilot.llm.service.LLMService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.HashMap;
import java.util.Map;

/**
 * LLM服务客户端（用于Agent Service）
 */
@Service
@Slf4j
public class LLMServiceClient {
    
    private final WebClient webClient;
    private final LLMService llmService;
    
    public LLMServiceClient(
            @Value("${services.llm.url:http://localhost:8086}") String llmServiceUrl,
            @Autowired(required = false) LLMService llmService) {
        this.llmService = llmService;
        this.webClient = WebClient.builder()
            .baseUrl(llmServiceUrl)
            .build();
    }
    
    public String generate(String prompt) {
        return generate(prompt, null);
    }
    
    public String generate(String prompt, String systemPrompt) {
        if (llmService != null) {
            try {
                LLMRequest request = LLMRequest.builder()
                    .prompt(prompt)
                    .systemPrompt(systemPrompt)
                    .build();
                
                Map<String, Object> result = llmService.generate(request);
                if (result != null && result.containsKey("content")) {
                    return result.get("content").toString();
                }
            } catch (Exception e) {
                log.error("Failed to generate with LLM service", e);
            }
        }
        
        // 如果LLM服务不可用，使用HTTP调用
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("prompt", prompt);
            if (systemPrompt != null) {
                request.put("systemPrompt", systemPrompt);
            }
            
            Map<String, Object> response = webClient.post()
                .uri("/llm/generate")
                .bodyValue(request)
                .retrieve()
                .bodyToMono(Map.class)
                .block();
            
            if (response != null && response.containsKey("content")) {
                return response.get("content").toString();
            }
        } catch (Exception e) {
            log.error("Failed to generate with HTTP client", e);
        }
        
        return "抱歉，LLM服务暂时不可用。";
    }
}

